package com.example.fszq.volleydemo1;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.StringRequest;
import com.example.fszq.volleydemo1.utils.MyUtil;
import com.example.fszq.volleydemo1.utils.Requesttoserver;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by fszq on 2016/1/3.
 */
public class UserLoginActivity  extends AppCompatActivity {
    private Button sButton;
    private TextView userName,passWord;

    private RequestQueue quence ;
    private Requesttoserver Rserver = new Requesttoserver();

    private MyUtil myUtil = new MyUtil(UserLoginActivity.this);
    private String cookieStr = "";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_login);

        //处理标题栏
        Toolbar toolbar = (Toolbar) findViewById(R.id.header_title);
        toolbar.setTitle("用户登录");
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);

        quence = Rserver.getRequestQueue(getApplicationContext());

        sButton = (Button)findViewById(R.id.sign_in_button);
        sButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                userLogin();
            }
        });

        userName = (TextView)findViewById(R.id.username);
        passWord = (TextView)findViewById(R.id.password);


    }

    private void userLogin() {
        String loginUrl = "http://www.c2000.cn/login.asp?action=chk";
        StringRequest stringRequest = new StringRequest(Request.Method.POST,loginUrl,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        //判断是否登录成功
                        if(response.indexOf("登录成功")!=-1) {
                            myUtil.saveShared("cookie", cookieStr);

                            //保存登录名字
                            myUtil.saveShared("userName", userName.getText().toString());

                            //判断登录成功
                            myUtil.saveShared("isLogin", "islogin");

                            //保存登录时间，以便提醒不够20秒不允许回复
                            myUtil.saveShared("loginTimeStamp",String.valueOf(System.currentTimeMillis()));
                            Log.d("loginTimeStamp", String.valueOf(System.currentTimeMillis()));

                            //返回上一级activity
                            Intent data = new Intent();
                            data.putExtra("loginResult",4);
                            setResult(RESULT_OK, data);
                            finish();

                        } else {
                            //
                            Toast.makeText(UserLoginActivity.this,"用户名或密码错",Toast.LENGTH_SHORT).show();
                        }
                    }
                }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("TAG", error.getMessage(), error);
            }


        }){

            @Override
            protected Response<String> parseNetworkResponse(NetworkResponse response) {
                String str = null;
                //String cookieStr = "";

                try {
                    //先判断是否登录成功

                    for (int i = 0; i < response.apacheHeaders.length; i++) {
                        String key = response.apacheHeaders[i].getName();
                        String value = response.apacheHeaders[i].getValue();
                        //处理返回的cookie
                        if(key.indexOf("Set-Cookie")>=0) {
                            value = value.substring(0,value.indexOf(";"));
                            cookieStr = value + "; " + cookieStr;
                        }

                        Log.d("VOLLEY_HEADERFIX",key + " - " +value);
                    }
                    //保存cookie
                    cookieStr = cookieStr + "Dvbbs=";


                    str = new String(response.data, "gb2312");//这里写死不好哦
                } catch (UnsupportedEncodingException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                return Response.success(str, HttpHeaderParser.parseCacheHeaders(response));
            }

            @Override
            protected String getParamsEncoding() {
                return "gbk";
            }

            @Override
            protected Map<String, String> getParams() {
                //在这里设置需要post的参数
                Map<String, String> map = new HashMap<String, String>();
                map.put("username", userName.getText().toString());
                map.put("password", passWord.getText().toString());
                map.put("CookieDate","0");
                map.put("userhidden","2");
                map.put("comeurl","list.asp%3Fboardid%3D1");
                map.put("submit","%B5%C7+%C2%BC");

                return map;
            }
        };

        quence.add(stringRequest);
    }

}
